package com.ruoyi.site.controller;

import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.exception.GlobalExceptionHandler;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.site.service.IOrderDetailsService;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.site.domain.Tracks;
import com.ruoyi.site.service.ITracksService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import static com.ruoyi.common.utils.ServletUtils.getRequest;
import com.ruoyi.site.service.IUserLicensesService;

/**
 * 音乐曲目Controller
 * 
 * @author chuckeytang
 * @date 2025-08-17
 */
@RestController
@RequestMapping("/site/tracks")
public class TracksController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(TracksController.class);
    @Autowired
    private ITracksService tracksService;

    @Autowired(required = false)
    private TokenService tokenService;

    @Autowired
    private IUserLicensesService userLicensesService;

    /**
     * 查询音乐曲目列表
     */
    @PostMapping("/list")
    public TableDataInfo list(@RequestBody Tracks tracks)
    {
        startPage();
        List<Tracks> list = tracksService.selectTracksList(tracks);
        return getDataTable(list);
    }

    /**
     * 导出音乐曲目列表
     */
    @Log(title = "音乐曲目", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Tracks tracks)
    {
        List<Tracks> list = tracksService.selectTracksList(tracks);
        ExcelUtil<Tracks> util = new ExcelUtil<Tracks>(Tracks.class);
        util.exportExcel(response, list, "音乐曲目数据");
    }

    /**
     * 获取音乐曲目详细信息
     */
    @GetMapping(value = "/{trackId}")
    public AjaxResult getInfo(@PathVariable("trackId") Long trackId)
    {
        return success(tracksService.selectTracksByTrackId(trackId));
    }

    /**
     * 新增音乐曲目
     */
    @PreAuthorize("@ss.hasPermi('site:tracks:add')")
    @Log(title = "音乐曲目", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Tracks tracks)
    {
        return toAjax(tracksService.insertTracks(tracks));
    }

    /**
     * 修改音乐曲目
     */
    @PreAuthorize("@ss.hasPermi('site:tracks:edit')")
    @Log(title = "音乐曲目", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Tracks tracks)
    {
        return toAjax(tracksService.updateTracks(tracks));
    }

    /**
     * 删除音乐曲目
     */
    @PreAuthorize("@ss.hasPermi('site:tracks:remove')")
    @Log(title = "音乐曲目", businessType = BusinessType.DELETE)
	@DeleteMapping("/{trackIds}")
    public AjaxResult remove(@PathVariable Long[] trackIds)
    {
        return toAjax(tracksService.deleteTracksByTrackIds(trackIds));
    }

    @GetMapping("/download/{trackId}")
    public void downloadFile(@PathVariable("trackId") Long trackId, HttpServletResponse response) {

        // 1. 获取用户ID
        Long currentUserId = null;
        try {
            LoginUser loginUser = tokenService.getLoginUser(getRequest());
            currentUserId = loginUser.getUserId();
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401
            return;
        }

        // 2. 检查购买状态 - 使用 UserLicenses Service
        boolean hasLicense = userLicensesService.checkUserHasLicense(currentUserId, trackId, "track"); // <--- 使用授权服务

        if (!hasLicense) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN); // 403
            return;
        }

        // 3. 获取文件信息
        Tracks track = tracksService.selectTracksByTrackId(trackId);
        if (track == null || StringUtils.isEmpty(track.getAudioFileUrl())) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // 4. 执行下载
        try (InputStream inputStream = new URL(track.getAudioFileUrl()).openStream()) {

            // 5. 记录下载次数
            // 假设 recordDownloadByProduct 已在 UserLicensesServiceImpl 中实现
            try {
                userLicensesService.recordDownloadByProduct(currentUserId, trackId, "track");
            } catch (Exception logE) {
                // 记录日志，但不中断下载流程
                log.error("Failed to record download count for userId: {}, trackId: {}", currentUserId, trackId, logE);
            }

            // 6. 设置响应头
            response.setContentType("audio/mpeg");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(track.getTitle() + ".mp3", "UTF-8"));

            // 7. 复制流
            IOUtils.copy(inputStream, response.getOutputStream());
            response.flushBuffer();

        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            e.printStackTrace();
        }
    }

    /**
     * 获取筛选器选项
     */
    @GetMapping("/filter-options")
    public AjaxResult getFilterOptions() {
        return success(tracksService.getFilterOptions());
    }

    /**
     * 检查用户是否拥有指定音乐曲目的下载授权
     */
    @GetMapping("/check-license/{trackId}")
    public AjaxResult checkLicense(@PathVariable("trackId") Long trackId) {
        try {
            // 1. 获取当前登录用户ID
            Long currentUserId = tokenService.getLoginUser(getRequest()).getUserId();

            // 2. 检查授权
            boolean hasLicense = userLicensesService.checkUserHasLicense(currentUserId, trackId, "track");

            if (hasLicense) {
                // 授权存在
                return success("License granted.");
            } else {
                // 授权不存在，返回 403 错误或自定义错误码
                // 为了让前端 Axios 拦截器能明确处理，我们返回 code: 403
                return AjaxResult.error(403, "License required for download.");
            }
        } catch (Exception e) {
            // 处理用户未登录或Token无效的异常
            return AjaxResult.error(401, "User not authenticated.");
        }
    }
}
